import fetch from "../../utils/fetch";
const globalData = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    triggered: false, //自定义下拉刷新状态
    dataList: [],
    type: 1, //列表类型，1为关注列表，2为粉丝列表
    title: '关注列表'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.type == 1) {
      this.getFollowList();
    } else {
      this.setData({
        title: '粉丝列表'
      })
      this.getFansList();
    }
  },
  //获取关注列表
  getFollowList() {
    fetch('/fans/followList', {
      noticerId: globalData.userInfo.id
    }).then(res => {
      console.log(res);
      this.setData({
        dataList: res.data.follows,
        triggered: false
      });
    }).catch(err => {
      this.getFollowList();
    })
  },

  //获取粉丝列表
  getFansList() {
    fetch('/fans/fansList', {
      followerId: globalData.userInfo.id
    }).then(res => {
      this.setData({
        dataList: res.data.fans,
        triggered: false
      });
    }).catch(err => {
      this.getFansList();
    })
  },
  changeConcern(e){
    const idx = e.currentTarget.dataset.idx;
    const isConcern = this.data.dataList[idx].isConcern;
    const user = this.data.dataList[idx].user;
    if(isConcern){
      wx.showModal({
        title: '关注',
        content: '确定取消关注吗',
        complete: (res) => {
          if (res.confirm) {
            fetch('/users/unfollow',{
              noticerId:globalData.userInfo.id,
              followerId:user.id
            }).then(res=>{
              this.setData({
                [`dataList[${idx}].isConcern`]:!isConcern
              });
              wx.showToast({
                title: '取消关注',
                icon:'error',
              })
            }).catch(err=>{
              this.changeConcern(e);
            })
          }
        }
      })
    }else{
      fetch('/users/follow',{
        noticerId:globalData.userInfo.id,
        followerId:user.id
      }).then(res=>{
        this.setData({
          [`dataList[${idx}].isConcern`]:!isConcern
        });
        wx.showToast({
          title: '关注成功',
          icon:'success'
        })
      }).catch(err=>{
          this.changeConcern(e);
      })
    }
  },
  gotoCenter(e){
    const userId = e.currentTarget.dataset.userId;
    wx.navigateTo({
      url: `../personalCenter/personalCenter?userId=${userId}`,
    })
  }
})